import subprocess
import traceback

from py.handler.msg_handler_abc import MsgHandlerAbc
from py.uitls import WinUtil


class MsgHandlerCmd(MsgHandlerAbc):
    def handle(self, title, content):
        try:
            # 为了兼容执行多行cmd命令，使用&&代替换行
            content = content.replace('\n', ' && ')

            # 处理掉多个换行导致的多个&&
            while True:
                content = content.replace(' &&  && ', ' && ')
                if ' &&  && ' not in content:
                    break

            res_content = WinUtil.exe_cmd(content)
            title = '执行CMD命令成功！'
        except Exception as result:
            title = '执行CMD命令失败！'
            res_content = traceback.format_exc()
        msg = '<p>已执行以下命令：</p><p>%s</p>' % content
        res_content = res_content.replace("\r\n\r\n", "<br/>")
        msg = msg + '<p>执行返回结果：</p><p>%s</p>' % res_content
        return title, msg, None
